
/**
 * Date:2019年5月31日下午2:35:31
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.common.coder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.xue.im.common.IMUtil.MessageType;
import com.xue.im.common.vo.Header;
import com.xue.im.common.vo.Message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * Description: 消息解码器 <br/>
 * Date: 2019年5月31日 下午2:35:31 <br/>
 * 
 * @author xuejianxin
 */
public class MessageDecoder extends LengthFieldBasedFrameDecoder {
	private final MyMarshallingDecoder marshallingDecoder;

	public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) throws IOException {
		// 注意这里
		super(maxFrameLength, lengthFieldOffset, lengthFieldLength, -(lengthFieldOffset + lengthFieldLength),
				lengthFieldOffset + lengthFieldLength);
		this.marshallingDecoder = new MyMarshallingDecoder();
	}

	@Override
	protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {

		try {
		ByteBuf frame = (ByteBuf) super.decode(ctx, in);
		if (frame == null) {
			return null;
		}
		in = frame;
		Message message = new Message();
		Header h = new Header();
		// h.setCrcCode(in.readInt());// 魔数
		// h.setLength(in.readInt());// 消息长度
		//h.setSessionId(in.readLong());// 会话id
		h.setType(in.readByte());// 消息类型
		//h.setPriority(in.readByte());// 优先级
		int size = in.readInt();// 附件长度
		// System.out.println(h+"-->"+size);
		if (size > 0) {
			Map<String, Object> attch = new HashMap<>(size);
			int keySize = 0;
			byte[] keyArray = null;
			String key = null;
			for (int i = 0; i < size; i++) {
				keySize = in.readInt();
				keyArray = new byte[keySize];
				in.readBytes(keyArray);
				key = new String(keyArray, "UTF-8");
				attch.put(key, marshallingDecoder.decode(in));
			}
			keyArray = null;
			key = null;
			h.getOptions().putAll(attch);
		}

		if (in.readableBytes() > 4) {
			message.setBody(marshallingDecoder.decode(in));
		}
		message.setHeader(h);
		if (h.getType() != MessageType.HEARTBEAT_REQ.value() && h.getType() != MessageType.HEARTBEAT_RESP.value()) {
			System.out.println("#####收到收到收到收到收到收到：" + message);
		}
		return message;
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}

}
